#This script executes event-study regressions to estimate cohort-specific 
#associations between first-generation prenatal exposure to nonattainment 
#and second-generation college attendance.

rm(list=ls())
gc()
library(reldist)
library(ineq)
library(stargazer)
library(data.table)
library(dplyr)
library(dtplyr)
library(ggplot2)
library(stringdist)
library(lfe)
library(haven)
library(readr)
library(broom)
library(tidylog)
library(rdrobust)

# Set the working directory
setwd("/projects/opp_env/caa1970/")

# Source external R scripts for custom functions
source("Code/Child_Outcomes/child_outcomes_functions.R")
source("Code/rounding.r")

# Load the second-generation analysis dataset
load("Data/second_gen_college_analysis_data_jpemicro.rda")

# Event Study

## Fig 2 - Second-Generation College Attendance

event2 <- felm(incollege ~inst_1969+inst_1970+inst_1972+
                 inst_1973+inst_1974+inst_1975 |state_year+county_factor+year_factor+month+
                 survey_year_by_year | 0 |county_factor,                
               data=regdata%>% filter(year%in%1969:1975, !is.na(all_fullterm), !is.na(parent_race), !is.na(PI_PC))) 
summary(event2)

#Save the underlying point
fig2 <- event2 %>% tidy() %>% mutate_each(funs(signif(.,4)),-term)  %>% 
  filter(grepl("inst", term), !is.na(estimate))%>%
  mutate(year=as.numeric(gsub("inst_","", gsub("_bin", "", term)))) %>% 
  bind_rows(., data.frame(estimate=0, std.error=0, year=1971)) %>% filter(year<=1975) 
write.csv(fig2, file="JPE_Micro/Output/Figure 2/Fig2.csv", row.names=F)
